﻿using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

public class ImportTexture : AssetPostprocessor
{
    public override uint GetVersion() { return 2; }
    static bool isForceImport = false;
    static string uiPath = "resourcesab/sprite/";
    static string effPath = "arts/effect/texture";

    static string[] mipmapPath = new string[]{
        "resourcesab/fbx/poker",
        "resourcesab/role/",
    };
    static string[] path512 = new string[]{
        "resourcesab/fbx/poker",
        "resourcesab/role/",
    };
    static string[] crunchRGBAPath = new string[]{
        "hu_shandian.png",
        "caihong.png",
    };

    //资源变化时处理
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        isForceImport = false;

        //移动资源的处理
        foreach (string str in movedAssets)
        {
            if (str.ToLower().Contains(uiPath))
            {
                isForceImport = true;

                // 如果是移动到指定UI目录下，需要重新Import
                AssetDatabase.ImportAsset(str);
            }
        }

        foreach (string asset in importedAssets)
        {
            string path = asset;
            if (path.ToLower().Contains("assets/resourcesab/lua/pb"))
            {
                FileInfo file = new FileInfo(path);
                SetBundles.SetOneResBundleName(file);
            }

            if (path.ToLower().Contains("assets/resourcesab") && path.EndsWith(".spriteatlas"))
            {
                SpriteAtlas atlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(path);
                var setting = atlas.GetPlatformSettings("Standalone");
                setting.overridden = true;
                setting.maxTextureSize = 2048;
                setting.format = TextureImporterFormat.DXT5;
                atlas.SetPlatformSettings(setting);

                setting = atlas.GetPlatformSettings("iPhone");
                setting.overridden = true;
                setting.maxTextureSize = 2048;
                setting.format = TextureImporterFormat.ASTC_6x6;
                atlas.SetPlatformSettings(setting);

                setting = atlas.GetPlatformSettings("Android");
                setting.overridden = true;
                setting.maxTextureSize = 2048;
                setting.format = TextureImporterFormat.ASTC_6x6;
                atlas.SetPlatformSettings(setting);
            }
        }
    }

    bool ContainPath(string[] paths, string assetPath)
    {
        foreach (var item in paths)
        {
            if (assetPath.Contains(item))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 音频导入后
    /// </summary>
    /// <param name="clip"></param>
    void OnPostprocessAudio(AudioClip clip)
    {
        if (!assetPath.ToLower().Contains("assets/resourcesab") && !assetPath.ToLower().Contains("assets/arts"))
        {
            return;
        }
        AudioImporter importer = assetImporter as AudioImporter;
        if (importer.userData != GetVersion().ToString())
        {
            importer.userData = GetVersion().ToString();

            importer.ambisonic = false;
            importer.preloadAudioData = false;
            importer.forceToMono = true;//clip.channels <= 1;

            AudioImporterSampleSettings setting = importer.defaultSampleSettings;
            // setting.sampleRateSetting = AudioSampleRateSetting.OverrideSampleRate;
            // setting.sampleRateOverride = 22050;

            setting.compressionFormat = AudioCompressionFormat.Vorbis;

            if (clip.length > 5)
            {
                importer.loadInBackground = true;
                setting.loadType = AudioClipLoadType.Streaming;
                // setting.quality = 0.3f;
            }
            else if (clip.length > 1)
            {
                importer.loadInBackground = false;
                setting.loadType = AudioClipLoadType.CompressedInMemory;
            }
            else
            {
                importer.loadInBackground = false;
                setting.loadType = AudioClipLoadType.DecompressOnLoad;
            }

            importer.defaultSampleSettings = setting;
            // importer.SaveAndReimport();
        }
    }

    /// <summary>
    /// 图片导入前处理
    /// </summary>
    void OnPreprocessTexture()
    {
        if (!assetPath.ToLower().Contains("assets/resourcesab") && !assetPath.ToLower().Contains("assets/arts"))
        {
            return;
        }
        // Debug.LogError(assetPath);
        if (assetPath.EndsWith(".dds"))
        {
            Debug.LogError("禁止使用dds格式图片，请检查：" + assetPath);
            return;
        }
        if (!assetPath.StartsWith("Assets"))
        {
            return;
        }

        TextureImporter importer = assetImporter as TextureImporter;
        if (importer.userData != GetVersion().ToString())
        {
            importer.userData = GetVersion().ToString();

            if (importer.textureType == TextureImporterType.SingleChannel)
            {
                return;
            }
            TextureImporterPlatformSettings setting = importer.GetDefaultPlatformTextureSettings();
            (int width, int height) = GetTextureImporterSize(importer);

            if (width > 2048 || height > 2048) Debug.LogWarningFormat("{0} 大小超过2048，已默认修改为2048，请自行检查，如需要请手动更改大小", assetPath);

            if (importer.textureType == TextureImporterType.SingleChannel)
            {
                return;
            }
            importer.isReadable = false;                                                    //可读写属性
            importer.npotScale = TextureImporterNPOTScale.None;

            string assetPathToLower = assetPath.ToLower();

            if (assetPathToLower.Contains(uiPath))
            {
                importer.textureType = TextureImporterType.Sprite;                              //精灵
                importer.wrapMode = TextureWrapMode.Clamp;                                      //采样模式
                importer.filterMode = FilterMode.Bilinear;                                      //纹理拉伸时过滤模式
                importer.spritePixelsPerUnit = 100;                                             //每单位像素数
                importer.alphaIsTransparency = importer.DoesSourceTextureHaveAlpha();           //透明通道是否透明
            }

            bool mipmap = ContainPath(mipmapPath, assetPathToLower);
            importer.mipmapEnabled = mipmap;

            bool max512 = ContainPath(path512, assetPathToLower);
            if (max512)
            {
                setting.maxTextureSize = 512;
            }
            else
            {
                setting.maxTextureSize = 2048;
            }

            setting.textureCompression = TextureImporterCompression.Compressed;
            importer.SetPlatformTextureSettings(setting);

            if (importer.textureType != TextureImporterType.NormalMap)
            {
                TextureImporterPlatformSettings settingStandalone = new TextureImporterPlatformSettings()
                {
                    name = "Standalone",
                    overridden = true,
                    maxTextureSize = setting.maxTextureSize,
                    format = importer.DoesSourceTextureHaveAlpha() ? TextureImporterFormat.DXT5 : TextureImporterFormat.DXT1,
                };
                importer.SetPlatformTextureSettings(settingStandalone);
            }

            TextureImporterPlatformSettings isettings = importer.GetPlatformTextureSettings("iPhone");
            isettings.overridden = true;
            isettings.maxTextureSize = setting.maxTextureSize;
            // bool isPowerOfTwo = IsPowerOfTwo(importer);
            // TextureImporterFormat defaultAlpha = isPowerOfTwo ? TextureImporterFormat.PVRTC_RGBA4 : TextureImporterFormat.ASTC_4x4;
            // TextureImporterFormat defaultNotAlpha = isPowerOfTwo ? TextureImporterFormat.PVRTC_RGB4 : TextureImporterFormat.ASTC_6x6;
            // isettings.format = importer.DoesSourceTextureHaveAlpha() ? defaultAlpha : defaultNotAlpha;

            bool divisible4 = IsDivisibleOf4(width, height);
            bool crunch = ContainPath(crunchRGBAPath, assetPathToLower);
            SetSetting(isettings, crunch, assetPathToLower, divisible4);

            importer.SetPlatformTextureSettings(isettings);

            TextureImporterPlatformSettings asettings = importer.GetPlatformTextureSettings("Android");
            asettings.overridden = true;
            asettings.allowsAlphaSplitting = false;
            asettings.maxTextureSize = setting.maxTextureSize;

            // defaultAlpha = divisible4 ? TextureImporterFormat.ETC2_RGBA8Crunched : TextureImporterFormat.ASTC_4x4;
            // defaultNotAlpha = divisible4 ? TextureImporterFormat.ETC_RGB4Crunched : TextureImporterFormat.ASTC_6x6;
            // asettings.format = importer.DoesSourceTextureHaveAlpha() ? defaultAlpha : defaultNotAlpha;

            SetSetting(asettings, crunch, assetPathToLower, divisible4);
            importer.SetPlatformTextureSettings(asettings);
            // importer.SaveAndReimport();
        }


    }
    void SetSetting(TextureImporterPlatformSettings isettings, bool crunch, string assetPathToLower, bool divisible4)
    {
        if (crunch)
        {
            isettings.format = divisible4 ? TextureImporterFormat.ETC2_RGBA8Crunched : TextureImporterFormat.ASTC_4x4;
        }
        else
        {
            isettings.format = TextureImporterFormat.ASTC_6x6;
        }
    }
    /// <summary>
    /// 图片导入后处理
    /// </summary>
    /// <param name="texture"></param>
    void OnPostprocessTexture(Texture2D texture)
    {
    }

    /// <summary>
    /// 是否2的次幂
    /// </summary>
    /// <param name="importer"></param>
    /// <returns></returns>
    bool IsPowerOfTwo(TextureImporter importer)
    {
        (int width, int height) = GetTextureImporterSize(importer);
        return (width == height) && (width > 0) && ((width & (width - 1)) == 0);
    }

    /// <summary>
    /// 是否2的次幂
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    bool IsPowerOfTwo(Texture2D texture)
    {
        return (texture.width == texture.height) && (texture.width > 0) && ((texture.width & (texture.width - 1)) == 0);
    }

    /// <summary>
    /// 是否被4整除
    /// </summary>
    /// <param name="importer"></param>
    /// <returns></returns>
    bool IsDivisibleOf4(TextureImporter importer)
    {
        (int width, int height) = GetTextureImporterSize(importer);
        return (width % 4 == 0 && height % 4 == 0);
    }

    /// <summary>
    /// 是否被4整除
    /// </summary>
    /// <param name="importer"></param>
    /// <returns></returns>
    bool IsDivisibleOf4(int width, int height)
    {
        return (width % 4 == 0 && height % 4 == 0);
    }
    /// <summary>
    /// 是否被4整除
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    bool IsDivisibleOf4(Texture2D texture)
    {
        return (texture.width % 4 == 0 && texture.height % 4 == 0);
    }

    /// <summary>
    /// 获取图片的尺寸 - 获取的是资源原始尺寸，不是unity内显示的
    /// </summary>
    /// <param name="importer"></param>
    /// <returns></returns>
    (int, int) GetTextureImporterSize(TextureImporter importer)
    {
        if (importer != null)
        {
            object[] args = new object[2];
            MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
            mi.Invoke(importer, args);
            return ((int)args[0], (int)args[1]);
        }
        return (0, 0);
    }
}